package com.zzt.zt_lifecycle.life;

import android.app.Activity;
import android.app.Application;
import android.os.Bundle;
import android.util.Log;

import androidx.annotation.NonNull;
import androidx.annotation.Nullable;


/**
 * @author: zeting
 * @date: 2021/5/19
 * 监听全局activity 生命周期
 * https://developer.android.google.cn/reference/kotlin/android/app/Application.ActivityLifecycleCallbacks?hl=en
 */
public class ActivityLifecycleObserver implements Application.ActivityLifecycleCallbacks {
    private static final String TAG = "LifecycleApp";

    private int mStartActivityCount;
    // 启动应用时间
    public long startAppTime = 0L;
    // 在线时间
    public long activityOnlineTime = 0L;


    public ActivityLifecycleObserver() {
    }

    @Override
    public void onActivityCreated(@NonNull Activity activity, @Nullable Bundle savedInstanceState) {
        Log.i(TAG, ">>>>>>>>> onActivityCreated ：" + activity.getComponentName().getClassName());
        if (mStartActivityCount == 0) {
            // 初始应用启动时间
            startAppTime = System.currentTimeMillis();
        }
    }

    @Override
    public void onActivityStarted(@NonNull Activity activity) {
        Log.i(TAG, ">>>>>>>>> onActivityStarted ：" + activity.getComponentName().getClassName());
        if (mStartActivityCount == 0) {
            // 首次启动
            Log.i(TAG, ">>>>>>>>> 首次启动 事件");


            // 初始化 activity 打开时间
            activityOnlineTime = System.currentTimeMillis();
        }
        mStartActivityCount++;
    }

    @Override
    public void onActivityResumed(@NonNull Activity activity) {
        Log.i(TAG, ">>>>>>>>> onActivityResumed ：" + activity.getComponentName().getClassName());
    }

    @Override
    public void onActivityPaused(@NonNull Activity activity) {

    }

    @Override
    public void onActivityStopped(@NonNull Activity activity) {
        Log.i(TAG, ">>>>>>>>> onActivityStopped ：" + activity.getComponentName().getClassName());
        mStartActivityCount--;
        Log.i(TAG, ">>>>>>>>> 存活保存数量:" + mStartActivityCount);
        if (mStartActivityCount == 0) {
            // 在线时间
            long duration = System.currentTimeMillis() - activityOnlineTime;
            Log.i(TAG, ">>>>>>>>> 在线时间 act 1:" + duration);
        }
    }

    @Override
    public void onActivitySaveInstanceState(@NonNull Activity activity, @NonNull Bundle outState) {

    }

    @Override
    public void onActivityDestroyed(@NonNull Activity activity) {
        Log.i(TAG, ">>>>>>>>> onActivityDestroyed ：" + activity.getComponentName().getClassName());
        Log.i(TAG, ">>>>>>>>> 存活保存数量:" + mStartActivityCount);
        if (mStartActivityCount == 0) {
            // 在线时间
            long duration = System.currentTimeMillis() - startAppTime;
            Log.i(TAG, ">>>>>>>>> 在线时间 app 2:" + duration);
        }
    }
}
